<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 信息区域 -->
      <el-alert title="添加商品信息" type="info" center :closable="false" show-icon></el-alert>
      <el-row>
        <el-steps finish-status="success" align-center :active="activeStep">
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step status="success" title="完成"></el-step>
        </el-steps>
      </el-row>
      <el-row>
        <el-form
          :model="addForm"
          ref="addFormRef"
          :rules="addFormRules"
          label-width="80px"
          label-position="top"
        >
          <el-tabs
            v-model="activeIndex"
            tab-position="left"
            :before-leave="beforeTabSwitch"
            @tab-click="tabSwitch"
          >
            <!-- 基本信息分页 -->
            <el-tab-pane label="基本信息" name="0">
              <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="addForm.goods_name"></el-input>
              </el-form-item>
              <el-form-item label="商品价格(元)" prop="goods_price">
                <el-input v-model="addForm.goods_price"></el-input>
              </el-form-item>
              <el-form-item label="商品重量(千克)" prop="goods_weight">
                <el-input v-model="addForm.goods_weight"></el-input>
              </el-form-item>
              <el-form-item label="商品数量" prop="goods_number">
                <el-input v-model.number="addForm.goods_number"></el-input>
              </el-form-item>
              <el-form-item label="商品分类" prop="goods_cat">
                <!-- 商品分类级联框 -->
                <el-cascader
                  clearable
                  filterable
                  v-model="addForm.goods_cat"
                  :options="categories"
                  :props="categoryProps"
                  @change="seletedCategoryChanged"
                ></el-cascader>
              </el-form-item>
            </el-tab-pane>
            <!-- 商品参数分页 -->
            <el-tab-pane label="商品参数" name="1">
              <!-- 循环动态参数组 -->
              <el-form-item
                :label="item.attr_name"
                v-for="item in dynamicAttrs"
                :key="item.attr_id"
              >
                <!-- 动态参数值渲染为复选框组 -->
                <el-checkbox-group v-model="item.attr_vals">
                  <el-checkbox
                    :label="val"
                    v-for="(val, index) in item.attr_vals"
                    :key="index"
                    border
                  ></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-tab-pane>
            <!-- 商品属性分页 -->
            <el-tab-pane label="商品属性" name="2">
              <!-- 循环渲染静态属性列表 -->
              <el-form-item :label="item.attr_name" v-for="item in staticAttrs" :key="item.attr_id">
                <el-input v-model="item.attr_vals"></el-input>
              </el-form-item>
            </el-tab-pane>
            <!-- 商品图片分页 -->
            <el-tab-pane label="商品图片" name="3">
              <el-upload
                :action="uploadURL"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                list-type="picture"
                :headers="imgHeader"
                multiple
                :accept="acceptFormat"
              >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-tab-pane>
            <!-- 商品内容分页 -->
            <el-tab-pane label="商品内容" name="4">
              <quill-editor v-model="addForm.goods_introduce"></quill-editor>
              <el-button type="primary" @click="addItem">添加商品</el-button>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </el-row>
    </el-card>
    <!-- 预览图片弹出框 -->
    <el-dialog title="图片预览" :visible.sync="imgPreviewDialogVisible" width="60%">
      <img :src="previewImgPath" alt />
    </el-dialog>
  </div>
</template>

<script>
import _ from "lodash";

export default {
  data() {
    // 数字验证规则
    const checkNumber = (rule, value, callback) => {
      if (value.toString().trim().length < 1) {
        return callback(new Error("不能为空"));
      }
      if (isNaN(value)) {
        return callback(new Error("必须为数字值"));
      } else if (value <= 0) {
        return callback(new Error("必须大于0"));
      }
      callback();
    };
    // 商品分类验证规则
    const checkCat = (rule, value, callback) => {
      if (!value || (value.length !== undefined && value.length < 3)) {
        return callback(new Error("必须选择商品分类"));
      }
      callback();
    };
    return {
      activeStep: 0,
      activeIndex: "0",
      addForm: {
        /* goods_name: "123",
        goods_price: 2,
        goods_weight: 5,
        goods_number: 0,
        goods_cat: [1, 3, 6], */
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: "",
        attrs: []
      },
      addFormRules: {
        goods_name: [
          {
            required: true,
            message: "请输入商品名称",
            trigger: "blur"
          }
        ],
        goods_price: [
          {
            required: true,
            validator: checkNumber,
            trigger: "blur"
          }
        ],
        goods_weight: [
          {
            required: true,
            validator: checkNumber,
            trigger: "blur"
          }
        ],
        goods_number: [
          {
            required: true,
            message: "数量不能为空",
            trigger: "blur"
          },
          {
            type: "number",
            min: 0,
            max: 9999,
            message: "数量必须为数字类型且介于0~9999之间",
            trigger: "blur"
          }
        ],
        goods_cat: [
          {
            required: true,
            validator: checkCat
          }
        ]
      },
      // 分类信息
      categories: [],
      categoryProps: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children"
      },
      // 参数信息
      dynamicAttrs: [],
      staticAttrs: [],
      selectedDynamicAttrVals: [],
      // 图片上传
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      acceptFormat: ".jpg,.png,.bmp",
      imgHeader: { Authorization: window.sessionStorage.getItem("token") },
      imgPreviewDialogVisible: false,
      previewImgPath: ""
    };
  },
  methods: {
    async getCategories() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类列表失败");
      }
      this.categories = res.data;
    },
    seletedCategoryChanged() {
      // 新增商品的分类必须是三级分类
      if (this.addForm.goods_cat.length < 3) {
        this.addForm.goods_cat = [];
        // return;
      }
    },
    // tab切换验证
    beforeTabSwitch(activeName, beforeName) {
      let validResult = true;
      if (beforeName === "0") {
        this.$refs.addFormRef.validate(valid => (validResult = valid));
      }
      return validResult;
    },
    // 分页点击切换事件
    tabSwitch(tab) {
      if (tab.index !== this.activeIndex) return;
      if (tab.index === "1") {
        this.getAttrs("many");
      } else if (tab.index === "2") {
        this.getAttrs("only");
      }
    },
    // 获取参数/属性
    async getAttrs(sel) {
      const { data: res } = await this.$http.get(
        `categories/${this.selectedCategoryId}/attributes`,
        { params: { sel } }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数/属性失败");
      }
      if (sel === "many") {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        });
      }
      this[sel === "many" ? "dynamicAttrs" : "staticAttrs"] = res.data;
    },
    // 图片上传相关
    handlePreview(file) {
      // file为当前被点击的上传文件的实例对象
      this.previewImgPath = file.response.data.url;
      this.imgPreviewDialogVisible = true;
    },
    handleRemove(file) {
      // 找到正被移除的文件的下标
      const index = this.addForm.pics.findIndex(
        pic => pic.path === file.response.data.tmp_path
      );
      this.addForm.pics.splice(index, 1);
      console.log(this.addForm.pics);
    },
    handleSuccess(res) {
      this.addForm.pics.push({ path: res.data.tmp_path });
    },
    addItem() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error("请完成必填项的填写");
        }
        const formData = _.cloneDeep(this.addForm);
        formData.goods_cat = formData.goods_cat.join(",");
        this.dynamicAttrs.forEach(attr => {
          formData.attrs.push({
            attr_id: attr.attr_id,
            attr_value: attr.attr_vals.join(" ")
          });
        });
        this.staticAttrs.forEach(attr => {
          formData.attrs.push({
            attr_id: attr.attr_id,
            attr_value: attr.attr_vals
          });
        });
        const { data: res } = await this.$http.post("goods", formData);
        if (res.meta.status !== 201) {
          return this.$message.error("添加商品失败");
        }
        this.$message.success("添加商品成功");
        this.$router.push("/goods");
      });
    }
  },
  computed: {
    selectedCategoryId() {
      return this.addForm.goods_cat.length < 3
        ? ""
        : this.addForm.goods_cat[this.addForm.goods_cat.length - 1];
    }
  },
  created() {
    this.getCategories();
  }
};
</script>

<style lang="less" scoped>
.el-dialog img {
  width: 100%;
}

.quill-editor ~ .el-button {
  margin-top: 15px;
}
</style>
